package com.jie.common.util;

import com.jie.common.exception.constant.ExceptionMessageConstant;
import com.jie.common.message.constant.MessageConstant;

import java.io.IOException;
import java.io.InputStream;

/**
 * 用于处理socket的inputStream的工具类
 * @author XieZhiJie
 * @date 2022/04/21 15:16
 */
public class InputStreamUtil {

    /**
     * 读取一个报文, 从报文头中得知报文长度, 并读取报文完整信息, 不包含报文头
     * @param inputStream  inputStream
     * @return             返回读取到的字节数组
     * @throws IOException IOException
     */
    public static byte[] readMessage(InputStream inputStream) throws IOException {
        return read(inputStream, BytesUtil.transformBytesToInt(read(inputStream, MessageConstant.MESSAGE_HEAD_LENGTH)));
    }

    /**
     * 从inputStream中读出length字节的数据才返回
     * @param inputStream inputStream
     * @param length      要读取的数据长度
     * @return            返回读取到的字节数组
     */
    public static byte[] read(InputStream inputStream, int length) throws IOException {
        byte[] results = new byte[length];
        int start = 0;
        int remain = length;
        int readLength;
        while ((readLength = inputStream.read(results, start, remain)) < remain) {
            if (readLength == -1) {
                throw new IOException(ExceptionMessageConstant.CONNECTION_TERMINATED);
            }
            // 读取不足, 继续读
            start += readLength;
            remain -= readLength;
        }
        return results;
    }

}
